package me.zhangyifeng.blog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.zhangyifeng.blog.model.domain.User;
import me.zhangyifeng.blog.model.dto.MaydayConst;

/**
 * 管理员拦截器，用于拦截管理员的请求
 */
@WebFilter(filterName = "adminFilter", urlPatterns = {"/admin/*"})
public class AdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String uri = httpRequest.getRequestURI();
        
        // 登录页面不需要拦截
        if (uri.contains("/admin/login") || uri.contains("/admin/getLogin")) {
            chain.doFilter(request, response);
            return;
        }
        
        // 获取session，判断用户是否已登录
        HttpSession session = httpRequest.getSession();
        User user = (User) session.getAttribute(MaydayConst.USER_SESSION_KEY);
        if (user == null) {
            httpResponse.sendRedirect("/admin/login");
            return;
        }
        
        // 检查权限：普通用户无法访问以下功能
        if (!user.getUserName().equals("admin") && (
                uri.contains("/admin/category") || 
                uri.contains("/admin/tag") || 
                uri.contains("/admin/page") || 
                uri.contains("/admin/attachment") || 
                uri.contains("/admin/theme") || 
                uri.contains("/admin/menus") || 
                uri.contains("/admin/links") || 
                uri.contains("/admin/option"))) {
            // 如果普通用户尝试访问管理员功能，重定向到仪表盘
            httpResponse.sendRedirect("/admin");
            return;
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
